import  re
from fastapi import Request,APIRouter
from Model.user.User import *
from Model.default import SessionLocal
from config.app_static_ import AI_HISTORY_RE
from func.qianfan import get_information

qianfan=APIRouter(prefix='/qianfan',tags=['qianfan'])
@qianfan.post("/qf/up_data")
async  def ai_post(request:Request,user_id:int):
    session=SessionLocal()
    Data= await request.json()
    data=Data['data']['data']
    ID = Data['data']['id']
    try:
        if  ID!='null':
                Tittle = re.match(AI_HISTORY_RE, data)[1]
                last=session.query(Ai_history).filter_by(tittle=Tittle,user_id=user_id,id=ID).first()
                last.text = data
                session.commit()
        else:

                Text_data = Ai_history()
                Tittle = re.match(AI_HISTORY_RE, data)[1]
                Text_data.tittle=Tittle
                Text_data.text = data
                Text_data.user_id = user_id
                session.add(Text_data)
                session.commit()
        return 1
    except Exception as e:
        print(e)
        pass
    finally:

        session.close()


@qianfan.get("/qf/use_qf")
async  def use_qf(qs:str,):
    try:
        data=str(await  get_information(qs))
        print(data)
        return  data
    except:
        return 0

@qianfan.get("/qf/get_data")
def get_user_history_Ai(user_id:int):
    session=SessionLocal()
    data_all = []
    try:
        data=session.query(Ai_history).filter_by(user_id=user_id).all()
        session.commit()
        for i in data:
            pre_Data={
                'Text':i.text,
                'id':i.id,
                'tittle':i.tittle
            }
            data_all.append(pre_Data)
        return data_all
    except Exception as e:
        print(e)
    finally:
        session.close()